<template>
  <div class="flex flex-col items-center  w-50%">
    <h2 class="font-size-36px fw-500 lh-24px mb-48px">找回密码</h2>
    <div class="p-20px w-full box-border bg-#fff">
      <el-form
        ref="findForm"
        class="login-form"
        :model="formData"
        :rules="rules"
        :show-message="false"
        label-position="top"
      >
        <template v-if="step === 1">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
              class="flex-1"
              v-model="formData.phoneNumber"
              placeholder="请输入"
            ></el-input>
            <el-button
              type="text"
              class="ml-40px"
              :class="{ 'is-sending': countDown }"
              @click="getCode"
              >{{ codeBtnText }}</el-button
            >
          </el-form-item>

          <el-form-item label="验证码" prop="code">
            <el-input v-model="formData.code" placeholder="请输入"></el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="新密码" prop="password">
            <PwdInput v-model="formData.password" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <PwdInput v-model="formData.confirmPassword" placeholder="请输入" />
          </el-form-item>
        </template>
      </el-form>
    </div>
    <div class="w-full mt-28px mb-30px flex justify-end font-size-16px">
      <span class="link cursor-pointer" @click="changeType('login')"
        >返回登录</span
      >
    </div>
    <el-button
      type="primary"
      class="w-full h-60px font-size-20px"
      :loading="loading"
      @click="doNext"
      >{{ confirmText }}</el-button
    >
  </div>
</template>

<script setup>
import { PwdInput } from "@/components";
import { useLoading } from "@/hooks";
import { phoneValidator } from "@/utils/valid";
import { dialogFunc } from "@/utils/dialogFunc";

const changeType = inject("changeType");
const { loading, setLoading } = useLoading();

const findForm = ref();
const formData = ref({
  phoneNumber: "",
  code: "",
  password: "",
  confirmPassword: "",
});
const confirmValid = (_, val, cb) => {
  if (!val) return cb(new Error("请再次确认密码"));
  if (val !== formData.value.password)
    return cb(new Error("两次输入密码不一致"));
  cb();
};
const rules = reactive({
  phoneNumber: [{ required: true, validator: phoneValidator, trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  confirmPassword: [
    { required: true, validator: confirmValid, trigger: "blur" },
  ],
});

const step = ref(1);
const confirmText = computed(() => (step.value === 1 ? "下一步" : "确认"));

const $api = inject("$api");
const doNext = () => {
  findForm.value.validate(async (valid) => {
    if (!valid) return;
    setLoading(true);
    if (step.value === 1) {
      // 校验验证码
      const { code, phoneNumber: username } = formData.value;
      try {
        const { data } = await $api.system.validCodeMsg({
          code,
          username,
        });
        formData.value.validCode = data;
        ++step.value;
      } finally {
        setLoading(false);
      }
    } else {
      // 重置密码
      try {
        const {
          phoneNumber: username,
          password,
          validCode: code,
        } = formData.value;
        await $api.system.resetPassword({
          username,
          password,
          code,
        });
        ElMessage.success("重置密码成功");
        setTimeout(() => {
          changeType("login");
        }, 500);
      } finally {
        setLoading(false);
      }
    }
  });
};

const countDown = ref(0);
const codeBtnText = computed(() => {
  return !countDown.value ? "获取验证码" : `已发送(${countDown.value}s)`;
});

const getCode = () => {
  if (countDown.value) return;
  findForm.value.validateField("phoneNumber", async (valid) => {
    if (!valid) return ElMessage.warning("请先输入正确的手机号");
    const data = await dialogFunc();
    doSendValidCode({
      ...data,
      username: formData.value.phoneNumber,
    });
  });
};
const doSendValidCode = async (data) => {
  await $api.system.sendCodeMsg(data);
  startCountDown();
};

const startCountDown = () => {
  countDown.value = 60;
  pollingCountDown();
};
const pollingCountDown = () => {
  setTimeout(() => {
    --countDown.value;
    if (countDown.value > 0) pollingCountDown();
  }, 1000);
};
</script>

<style scoped lang="less">
.is-sending {
  color: @text-light!important;
}
</style>
